package com.ruike.alisurface.ui.realAuth;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.usb.UsbDevice;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.TextureView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lgh.uvccamera.UVCCameraProxy;
import com.lgh.uvccamera.bean.PicturePath;
import com.lgh.uvccamera.callback.ConnectCallback;
import com.lgh.uvccamera.callback.PictureCallback;
import com.ruike.alisurface.Constant;
import com.ruike.alisurface.R;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.bean.CarGoodsBeans;
import com.ruike.alisurface.bean.IdcardBean;
import com.ruike.alisurface.bean.ShopOrderBean;
import com.ruike.alisurface.https.ShopApiHttp;
import com.ruike.alisurface.serialport.Ttys3Utils;
import com.ruike.alisurface.ui.ShopMain_Aty;
import com.ruike.alisurface.ui.payPage.ShopPayType_Aty;
import com.ruike.alisurface.utils.BitmipUtil;
import com.ruike.alisurface.utils.DateUtil;
import com.ruike.alisurface.utils.DialogTipUtils;
import com.ruike.alisurface.utils.FinalDbUtils;
import com.ruike.alisurface.utils.GsonUtils;
import com.ruike.alisurface.utils.OrcIdUtil;
import com.voodoo.lib_http.ApiListener;
import com.voodoo.lib_logcat.L;
import com.voodoo.lib_utils.Base64Util;
import com.voodoo.lib_utils.FileUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 身份证认证页
 */
public class RealNameAuth_Aty extends BaseAty implements ApiListener {


    @BindView(R.id.idcard_camare_lv)
    LinearLayout idcardCamareLv;
    @BindView(R.id.idcard_confirm_tv)
    TextView idcardConfirmTv;
    @BindView(R.id.to_back)
    ImageView toBack;
    @BindView(R.id.to_times)
    TextView toTimes;

    Handler mHandler = new Handler(Looper.getMainLooper());

    @Override
    protected int getLayoutResId() {
        return R.layout.app_realname_auth;
    }

    @Override
    protected void initViews() {
        initTitleBar(false);
        startCountdownTimer(120, toTimes, ShopMain_Aty.class);
        toBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(ShopMain_Aty.class, null);
                finish();
            }
        });
    }

    ShopOrderBean shopOrderBean;
    List<CarGoodsBeans> goodsBeansList = new ArrayList<>();

    @Override
    protected void initData() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String json = getIntent().getStringExtra("shopOrderBean");
            shopOrderBean = GsonUtils.fromJson(json, ShopOrderBean.class);
        }
        goodsBeansList.addAll(FinalDbUtils.getInstance().findAll(CarGoodsBeans.class));

    }

    @Override
    protected void onResume() {
        super.onResume();
        Constant.isShopShipment = true;
        Ttys3Utils.getInstance().ledOpenOrClose(0, 1, true, 15, 15);
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                initUVCCamera(12342);
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        Constant.isShopShipment = false;
        Ttys3Utils.getInstance().ledOpenOrClose(0, 1, false, 15, 15);

    }

    /**
     * 初始化UVC摄像头配置及操作
     */
    private UVCCameraProxy mUVCCamera;
    String mProductId;
    boolean isusb;

    private void initUVCCamera(int ProductId) {
        L.i("tjf-usb-", "开始初始化配置 == " + ProductId);
        TextureView textureView = new TextureView(this);
        idcardCamareLv.addView(textureView);
        mProductId = String.valueOf(ProductId);
        mUVCCamera = new UVCCameraProxy(this);
        // 已有默认配置，不需要可以不设置
        mUVCCamera.getConfig()
                .isDebug(true)
                .setPicturePath(PicturePath.SDCARD)
                .setDirName("/Images/")
                /* .setProductId(14371)
                 .setVendorId(1528);*/
                .setProductId(ProductId)
                .setVendorId(3034);

//        mVendorId=3034,mProductId=12342  根据USB摄像头来区分 mVendorId供应商id   mProductId 产品id   ProductId(12936)  日期1020
        mUVCCamera.setPreviewTexture(textureView);


        mUVCCamera.setConnectCallback(new ConnectCallback() {
            @Override
            public void onAttached(UsbDevice usbDevice) {
                mUVCCamera.requestPermission(usbDevice);
                L.i("tjf-usb-", "请求连接 ");
            }

            @Override
            public void onGranted(UsbDevice usbDevice, boolean granted) {
                if (granted) {
                    mUVCCamera.connectDevice(usbDevice);
                    L.i("tjf-usb-", "连接 ");
                } else {
                    L.i("tjf-usb-", "请求连接 ");
                    mUVCCamera.requestPermission(usbDevice);
                }
            }

            @Override
            public void onConnected(UsbDevice usbDevice) {
                L.i("tjf-usb-", "打开 ");
                isusb = true;
                mUVCCamera.openCamera();
            }

            @Override
            public void onCameraOpened() {
                L.i("tjf-usb-", "打开成功并设置预览及开始");
                mUVCCamera.setPreviewSize(2592, 1944);
                mUVCCamera.startPreview();
            }

            @Override
            public void onDetached(UsbDevice usbDevice) {
                L.i("tjf-usb-", "关闭连接");
                isusb = false;
            }
        });

     /*   mUVCCamera.setPhotographCallback(new PhotographCallback() {
            @Override
            public void onPhotographClick() {
//                mUVCCamera.takePicture();
//                mUVCCamera.takePicture("test.jpg");
            }
        });

        mUVCCamera.setPreviewCallback(new PreviewCallback() {
            @Override
            public void onPreviewFrame(byte[] yuv) {

            }
        });*/

        mUVCCamera.setPictureTakenCallback(new PictureCallback() {
            @Override
            public void onPictureTaken(final String path) {
                L.i("tjf-原图路径-" + path);
                cropFlieIDcard(path);
            }
        });
    }

    @OnClick({R.id.idcard_confirm_tv})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.idcard_confirm_tv:
                if (!isusb) {
                    showErrorToast("实名问诊相机未连接，请检查硬件");
                    return;
                }
                showProgressDialog("身份证信息识别中，请等待...", false);
                mUVCCamera.takePicture("test.jpg");
                break;
        }
    }


    public void cropFlieIDcard(String path) {
        FileUtils.checkFolderIsExists(Constant.FilePath.IDCARD_PATH, true);
        String filePath = BitmipUtil.cropBitmap(path);
        L.i("要识别裁剪后的的图片路径==" + filePath);
        getORCIdCard(filePath);
    }

    private String encodeImage(String path) {
        File imagefile = new File(path);
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(imagefile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Bitmap bm = BitmapFactory.decodeStream(fis);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] b = baos.toByteArray();
        String encImage = Base64Util.encode(b);
        //Base64.de
        return encImage;

    }


    public void getORCIdCard(String fileapth) {//该接口需要添加addHeader("Authorization", "APPCODE " + "ab3c45977cdb4b1693a58606e60fe51a")
//        String url = "https://dm-51.data.aliyun.com/rest/160601/ocr/ocr_idcard.json";
        OrcIdUtil.getORCIdCard(fileapth, this);

    }

    @Override
    protected void onPause() {
        super.onPause();
        removeProgressDialog();
        idcardCamareLv.removeAllViews();
    }

    @Override
    public void onRequestStart(String requestUrl, int requestId) {

    }

    @Override
    public void onRequestComplete(String requestUrl, int requestId) {
        if (requestUrl.endsWith("ocr_idcard.json")) {
            removeProgressDialog();
        }
    }

    @Override
    public void onSuccess(String requestUrl, JSONObject requestJson, int requestId) {
        if (requestUrl.endsWith("ocr_idcard.json")) {
            setIdCardData(requestJson.toString());
            return;
        }
        if (requestUrl.endsWith(ShopApiHttp.handle_true_name_order)) {

// {"data":{"url":"http://www.shouhuojiyun.com/Rknew/App/order/Pay?OrderId=2021072315195500093737&TradeType=","id":"2021072315195500093737","pay_fee":0.01,"total_fee":0.01,"discount_fee":0.00,"promotion_fee":0.00,"details":[{"slotIndex":10,"quantity":1,"slotTypeId":21001}]},"code":0,"msg":"success","sendData":"2021-07-23 15:20:16"}
            removeProgressDialog();

            doStartActivity(ShopPayType_Aty.class, requestJson.toString());
        }
    }

    @Override
    public void onError(String requestUrl, String errorMsg, String resultData, int requestId) {
        if (requestUrl.endsWith("ocr_idcard.json")) {
            removeProgressDialog();

            DialogTipUtils.setErrorDialog(this);
            return;
        }
        if (requestUrl.endsWith(ShopApiHttp.handle_true_name_order)) {
            removeProgressDialog();
            showErrorLongToast(errorMsg, 4000);
        }
    }


    public void setIdCardData(String json) {
//        String idcard = "{\"address\":\"浙江省永嘉县碧莲镇澄田村澄川中路53号\",\"angle\":0,\"birth\":\"19891130\",\"card_region\":[{\"x\":80,\"y\":158},{\"x\":1517,\"y\":174},{\"x\":1542,\"y\":1118},{\"x\":44,\"y\":1101}],\"config_str\":\"{\\\"side\\\":\\\"face\\\"}\",\"face_rect\":{\"angle\":0,\"center\":{\"x\":1212,\"y\":589},\"size\":{\"height\":464,\"width\":542}},\"face_rect_vertices\":[{\"x\":981,\"y\":317},{\"x\":1446,\"y\":319},{\"x\":1444,\"y\":861},{\"x\":979,\"y\":860}],\"is_fake\":false,\"name\":\"陈建领\",\"nationality\":\"汉\",\"num\":\"330324198911306650\",\"request_id\":\"5484105A-56D2-4C02-8BB2-7271BDD0FF3A\",\"sex\":\"男\",\"success\":true}";
        IdcardBean idcardBean = new Gson().fromJson(json, IdcardBean.class);
        try {
            JSONObject orderObject = new JSONObject();
            JSONArray product_list = new JSONArray();
            for (CarGoodsBeans dataBean : goodsBeansList) {
                JSONObject productobject = new JSONObject();
                productobject.put("productid", dataBean.getProductid());
                productobject.put("quantity", 1);
                JSONArray mSlotIndexs = new JSONArray(dataBean.getMslotIndexs());
                productobject.put("slotIndexs", mSlotIndexs);
                product_list.put(productobject);
            }
            orderObject.put("product_list", product_list);
            orderObject.put("order_id", shopOrderBean.getData().getId());
            orderObject.put("name", idcardBean.getName());
            orderObject.put("nationality", idcardBean.getNationality());
            orderObject.put("num", idcardBean.getNum());
            orderObject.put("sex", idcardBean.getSex());
            orderObject.put("address", idcardBean.getAddress());
            int age = 0;
            if (idcardBean.getNum().length() >= 18) {
                int oldyear = Integer.parseInt(idcardBean.getNum().substring(6, 10));
                int currentyear = DateUtil.getYearDate(new Date(System.currentTimeMillis()));
                age = currentyear - oldyear;
            }
            orderObject.put("age", age);
            L.i("Idcard 信息=", orderObject.toString());
            if (!idcardBean.isSuccess()) {
                showErrorLongToast("身份证识别失败，请重新识别", 4000);
                return;
            }
            if (idcardBean.isIs_fake()) {
                removeProgressDialog();
                showErrorLongToast("请使用真实身份证实名身份", 4000);
                return;
            }

            ShopApiHttp.handle_true_name_order(orderObject.toString(), this);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        com.blankj.utilcode.util.FileUtils.deleteAllInDir(Constant.FilePath.IDCARD_PATH);
        shopOrderBean = null;
        goodsBeansList.clear();
        idcardCamareLv.removeAllViews();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler=null;
        }
    }
}
